import { Injectable,HttpException ,HttpStatus} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'
import { InjectRepository } from '@nestjs/typeorm'
import { User } from 'src/entities/user.entity';
import { Repository } from 'typeorm'
import { RigisterDto } from './dto/rigister.dto';

@Injectable()
export class AuthService {
    constructor(
        private readonly jwtService: JwtService,

        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        
    ) { }

    async createToken(userId: string) {
        return this.jwtService.sign({ userId })
    }

    validateToken(token) {
        if (!token) {
            return false
        }
        try {
            return this.jwtService.verify(token)
        }
        catch {
            return false
        }

    }

    async login({ email, password }) {
        const user = await this.userRepository.findOne({
            where: { email, password }
        })

        if (!user) {
            throw new HttpException('账号或密码错误', HttpStatus.UNAUTHORIZED)
        } else {
            const token = await this.createToken(user.id)
            return token
        }
    }

    async addUser(user:RigisterDto): Promise<void> {
        // 先判断用户是否存在
        const info = await this.userRepository.findOne({ where: { name: user.name } })
        if (info) { throw new HttpException('用户已注册', HttpStatus.BAD_REQUEST) }
        // 判断邮箱是否注册
        const email = await this.userRepository.findOne({ where: { email: user.email } })
        if (email) throw new HttpException('邮箱已注册', HttpStatus.BAD_REQUEST)
        await this.userRepository.save({...user,desc:"这个人很懒，什么都没有留下..."});

    }
}
